package com.lc.mqtt.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.study.common.constant.MqttConstant;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/11/13 11:35
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class MyMqttCallback implements MqttCallback {

    private MqttClient mqttClient;

    private MqttConnectOptions connOpts;

    private String proClient;

    /**
     * 连接中断后进行重连
     * 只会调用一次
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("{} 断开连接，异常信息：{}", mqttClient.getClientId(), throwable.getMessage());
        try {
            log.info("{} 开始重新连接...", mqttClient.getClientId());
            mqttClient.connect(connOpts);
            // 重新设置订阅
            if (proClient.equals(MqttConstant.LOCAL_MQTT_CLIENT)) {
                mqttClient.subscribe(MqttTopic.Topics);
                log.info("{} 重新订阅主题...", mqttClient.getClientId());
            }
        } catch (MqttException e) {
            log.error("{} 重新连接异常，异常信息：{}", mqttClient.getClientId(), ExceptionUtil.stacktraceToString(throwable));
        }
    }

    /**
     * subscribe后得到的消息会执行
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        log.info("接收消息,topic = {}, qos = {} content = {}", topic, mqttMessage.getQos(), new String(mqttMessage.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
